import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isHttp } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'
NProgress.configure({ showSpinner: false })

const whiteList = [
  '/login',
  '/adminlogin',
  '/auth-redirect',
  '/bind',
  '/register',
]

router.beforeEach((to, from, next) => {
   next()
  // 这边做路由拦截
  NProgress.start()
  // if (getToken()) {
  //   if (to.path === '/login' || to.path === '/adminlogin') {
  //     next({ path: '/user' })
  //     NProgress.done()
  //   }else if(to.path === '/'){
  //     next({ path: '/user' })
  //     NProgress.done()
  //   }else {
  //     if (!usePermissionStore().asyncRoutestMark) {
  //       usePermissionStore()
  //         .generateRoutes()
  //         .then((accessRoutes) => {
  //           // 根据权限生成可访问的路由表
  //           setButtonList(accessRoutes)
  //           accessRoutes.forEach((route) => {
  //             router.addRoute(route)
  //           })
  //           // console.log(router.getRoutes())
  //           console.log(from)
            
  //           console.log(to)
  //           const defaultRouteArr = ["allacset","saleman","basicInformation","basicInformationFinance","houselist","invoiclist","grossProfit","custom"]
  //           if(from.path === '/login' || from.path === '/adminlogin'){
  //             // console.log(router.getRoutes())
  //             // const defaultRoute = router.getRoutes()[1]
  //             router.getRoutes().forEach((item)=>{
  //               // console.log(item)
  //               if(defaultRouteArr.includes(item.name)){
  //                 // console.log(item)
  //                 next({ ...item, replace: true })
  //               }
  //             })
  //             // next({ ...defaultRoute, replace: true })
  //           }else{
  //             // console.log(to)
  //             next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  //           }
            
  //         })
  //       usePermissionStore().setAsyncRoutestMark(true) // 添加路由后更改标识为true
  //     } else {
  //       next()
  //     }

  //     // next()
  //   }
  // } else {
  //   // 没有token
  //   if (whiteList.indexOf(to.path) !== -1) {
  //     // 在免登录白名单，直接进入
  //     next()
  //   } else {
  //     next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
  //     NProgress.done()
  //   }
  // }
})

// 处理buttonlist
function setButtonList(data){
  // console.log(data)
  data.forEach((item)=>{
    if(item.children && item.children.length > 0){
      setButtonList(item.children)
    }else{
      item.meta['buttonlist'] = item.buttonlist
    }
  })
}


router.afterEach(() => {
  NProgress.done()
})
